<template>
  <div>
    <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>缺寝记录</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin: 15px; min-height: calc(100vh - 111px)">
      <div>
        <!-- 功能区 -->
        <div style="margin: 10px 0">
          <!-- 搜索区 -->
          <div style="margin: 10px 0">
            <el-input
              v-model="search"
              clearable
              placeholder="请输入姓名"
              prefix-icon="Search"
              style="width: 20%"
            />
            <el-button
              icon="Search"
              style="margin-left: 5px"
              type="primary"
              @click="fetchData"
            ></el-button>
            <el-button
              icon="refresh-left"
              style="margin-left: 10px"
              type="default"
              @click="reset"
            ></el-button>
            <div style="float: right">
              <el-tooltip content="添加" placement="top">
                <el-button
                  icon="plus"
                  style="width: 50px"
                  type="primary"
                  @click="add"
                ></el-button>
              </el-tooltip>
            </div>
          </div>
        </div>

        <!-- 表格 -->
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          max-height="705"
          style="width: 100%"
        >
          <el-table-column label="ID" prop="id" width="80px" />
          <el-table-column label="姓名" prop="name" width="100px" />
          <el-table-column label="性别" prop="gender" width="100px" />
          <!-- <el-table-column label="楼号" prop="dormBuildName" width="100px" /> -->
          <el-table-column
            label="楼号"
            prop="dormBuildName"
            width="100px"
            :filter-method="filterDormBuild"
            :filters="generateFilters()"
            filter-placement="bottom-end"
          />

          <el-table-column label="宿舍号" prop="dormroomId" width="100px" />
          <el-table-column label="缺寝时间" prop="missingTime" width="200px" />
          <el-table-column label="返回时间" prop="returnTime" width="200px" />
          <el-table-column label="缺寝原因" prop="reason" />
          <el-table-column label="宿管" prop="remarks" width="100px" />

          <!-- 操作栏 -->
          <el-table-column label="操作" width="180px">
            <template #default="scope">
              <el-button
                icon="Edit"
                type="primary"
                @click="handleEdit(scope.row)"
              ></el-button>

              <el-popconfirm
                title="确认删除？"
                @confirm="handleDelete(scope.row.id)"
              >
                <template #reference>
                  <el-button icon="Delete" type="danger"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="margin: 10px 0">
          <el-pagination
            v-model:currentPage="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentPageChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑弹出框 -->
    <!-- 添加/编辑弹出框 -->
    <el-dialog
      title="添加缺寝记录"
      v-model="dialogVisible"
      width="30%"
      @close="cancel"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入姓名"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select
            v-model="form.gender"
            placeholder="请选择性别"
            style="width: 80%"
          >
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼号" prop="dormBuildName">
          <el-select
            v-model="form.dormBuildName"
            placeholder="请选择楼号"
            style="width: 80%"
          >
            <el-option
              v-for="dorm in dormBuildfo"
              :key="dorm.dormBuildName"
              :label="dorm.dormBuildName"
              :value="dorm.dormBuildName"
            />
            <!-- <el-option label="一号楼" value="一号楼" />
            <el-option label="二号楼" value="二号楼" />
            <el-option label="三号楼" value="三号楼" />
            <el-option label="四号楼" value="四号楼" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="宿舍号" prop="dormroomId">
          <el-input
            v-model="form.dormroomId"
            placeholder="请输入宿舍号"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="缺寝时间" prop="missingTime">
          <el-date-picker
            v-model="form.missingTime"
            type="datetime"
            placeholder="请选择缺寝时间"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="返回时间" prop="returnTime">
          <el-date-picker
            v-model="form.returnTime"
            type="datetime"
            placeholder="请选择返回时间"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="缺寝原因" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            placeholder="请输入缺寝原因"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item label="宿管备注" prop="remarks">
          <el-select
            v-model="form.remarks"
            placeholder="请选择宿管"
            style="width: 80%"
          >
            <el-option :label="role.name" :value="role.name" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
 
<script>
import request from "@/utils/request";
import { ElMessage } from "element-plus";

export default {
  data() {
    return {
      tableData: [],
      search: "",
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      form: {
        name: "",
        gender: "",
        judge: false, // 判断当前是新增还是编辑状态
        dormBuildName: "",
        dormroomId: "",
        missingTime: null,
        returnTime: null,
        reason: "",
        remarks: "",
      },
      dormBuildfo: [], //存放楼宇信息
      role: "", // 存放当前用户的角色信息
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        dormBuildName: [
          { required: true, message: "请输入楼号", trigger: "blur" },
        ],
        dormroomId: [
          { required: true, message: "请输入宿舍号", trigger: "blur" },
        ],
        missingTime: [
          { required: true, message: "请选择缺寝时间", trigger: "change" },
        ],
       
        reason: [
          { required: true, message: "请输入缺寝原因", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.role = JSON.parse(window.sessionStorage.getItem("user")); // 获取当前登录用户信息
    this.dormBuild();
    this.fetchData();
    this.loading = true;
  },
  methods: {
    async fetchData() {
      request
        .get("/absent/find/", {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            search: this.search,
          },
        })
        .then((res) => {
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.loading = false;
        });
    },
    //用于筛选楼号
    generateFilters() {
      // 生成用于表格筛选的选项
      return this.dormBuildfo.map((dorm) => ({
        text: dorm.dormBuildName,
        value: dorm.dormBuildName,
      }));
    },
    filterDormBuild(value, row) {
      // 筛选逻辑
      return row.dormBuildName === value;
    },

    async dormBuild() {
      request
        .get("/building/find", {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            search: this.search,
          },
        })
        .then((res) => {
          console.log(res);
          console.log("111");
          this.dormBuildfo = res.data.records; // 将获取到的宿舍信息存储到 dormBuild
        });
    },
    reset() {
      this.search = "";
      request
        .get("/absent/find", {
          params: {
            pageNum: 1,
            pageSize: this.pageSize,
            search: this.search,
          },
        })
        .then((res) => {
          console.log(res);
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.loading = false;
        });
    },
    add() {
      this.dialogVisible = true; // 确保这里设置为 true
      this.$nextTick(() => {
        this.$refs.form.resetFields(); // 清除表单
        this.form = {}; // 重置表单数据
        this.judge = false; // 设置为新增状态
      });
    },
    save() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.judge === false) {
            // 新增
            await request.post("/absent/add", this.form).then((res) => {
              console.log(res);
              if (res.code === "0") {
                ElMessage({
                  message: "新增成功", // 提示信息
                  type: "success",
                });
                this.search = ""; // 清空搜索框
                this.fetchData(); // 重新加载数据
                this.dialogVisible = false; // 关闭弹窗
              } else {
                ElMessage({
                  message: res.msg, // 错误提示信息
                  type: "error",
                });
              }
            });
          } else {
            // 修改
            await request.put("/absent/update", this.form).then((res) => {
              console.log(res);
              if (res.code === "0") {
                ElMessage({
                  message: "修改成功", // 提示信息
                  type: "success",
                });
                this.search = ""; // 清空搜索框
                this.fetchData(); // 重新加载数据
                this.dialogVisible = false; // 关闭弹窗
              } else {
                ElMessage({
                  message: res.msg, // 错误提示信息
                  type: "error",
                });
              }
            });
          }
        }
      });
    },
    // 删除操作
    async handleDelete(id) {
      console.log(id);
      request.delete("/absent/delete/" + id).then((res) => {
        if (res.code === "0") {
          ElMessage({
            message: "删除成功", // 提示信息
            type: "success",
          });
          this.search = ""; // 清空搜索框
          this.fetchData(); // 重新加载数据
        } else {
          ElMessage({
            message: res.msg, // 错误提示信息
            type: "error",
          });
        }
      });
    },
    // 编辑操作
    handleEdit(row) {
      // 设置为编辑状态
      this.judge = true;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields(); // 重置表单
        this.form = JSON.parse(JSON.stringify(row)); // 复制当前行数据
        this.disabled = true; // 禁用表单项
      });
    },
    handlePageSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },

    handleCurrentPageChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    cancel() {
      this.$refs.form.resetFields();
      this.display = { display: "none" };
      this.editJudge = true;
      this.disabled = true;
      this.dialogVisible = false;
    },
  },
};
</script>

<style scoped>
.el-button {
  margin-left: 10px;
}
</style>